{% extends "base.html" %}

{% block title %}铃声库管理 - 铃声系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <i class="fas fa-music"></i> 音频文件列表
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-3">
                    <div>
                        <button id="refresh-audio" class="btn btn-outline-secondary">
                            <i class="fas fa-sync"></i> 刷新
                        </button>
                    </div>
                    <div>
                        <button id="upload-audio" class="btn btn-primary">
                            <i class="fas fa-upload"></i> 上传音频
                        </button>
                    </div>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th scope="col">#</th>
                                <th scope="col">文件名</th>
                                <th scope="col">路径</th>
                                <th scope="col">时长</th>
                                <th scope="col">上传时间</th>
                                <th scope="col">操作</th>
                            </tr>
                        </thead>
                        <tbody id="audio-table-body">
                            <!-- 音频文件列表将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 上传音频文件模态框 -->
<div class="modal fade" id="uploadModal" tabindex="-1" aria-labelledby="uploadModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="uploadModalLabel">上传音频文件</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="upload-form">
                    <div class="mb-3">
                        <label for="audio-file" class="form-label">选择音频文件</label>
                        <input class="form-control" type="file" id="audio-file" accept=".mp3,.wav,.ogg">
                        <div class="form-text">支持的格式: MP3, WAV, OGG (文件大小限制: 100MB)</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="upload-btn">上传</button>
            </div>
        </div>
    </div>
</div>

<!-- 试听音频模态框 -->
<div class="modal fade" id="previewModal" tabindex="-1" aria-labelledby="previewModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="previewModalLabel">试听音频</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">文件名:</label>
                    <div id="preview-filename"></div>
                </div>
                <div class="mb-3">
                    <label class="form-label">时长:</label>
                    <div id="preview-duration"></div>
                </div>
                <div class="mb-3">
                    <label class="form-label">音量:</label>
                    <div class="d-flex align-items-center">
                        <i class="fas fa-volume-down me-2"></i>
                        <input type="range" class="form-range" id="preview-volume" min="0" max="100" value="80">
                        <i class="fas fa-volume-up ms-2"></i>
                        <span id="volume-value" class="ms-2">80%</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="preview-stop" disabled>
                    <i class="fas fa-stop"></i> 停止
                </button>
                <button type="button" class="btn btn-success" id="preview-play">
                    <i class="fas fa-play"></i> 播放
                </button>
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 当前试听的音频信息
    let currentPreview = {
        id: null,
        filename: '',
        path: '',
        duration: 0
    };
    
    // 加载音频文件列表
    function loadAudioFiles() {
        fetch('/api/audio_files')
            .then(response => response.json())
            .then(files => {
                renderAudioFiles(files);
            })
            .catch(error => {
                console.error('加载音频文件列表失败:', error);
                alert('加载音频文件列表失败: ' + error.message);
            });
    }
    
    // 渲染音频文件列表
    function renderAudioFiles(files) {
        const tbody = document.getElementById('audio-table-body');
        tbody.innerHTML = '';
        
        files.forEach((file, index) => {
            const duration = file.duration > 0 ? `${file.duration}秒` : '未知';
            
            const row = document.createElement('tr');
            row.innerHTML = `
                <th scope="row">${index + 1}</th>
                <td>${file.filename}</td>
                <td>${file.path}</td>
                <td>${duration}</td>
                <td>${file.upload_time}</td>
                <td>
                    <button class="btn btn-sm btn-outline-info preview-audio" 
                            data-id="${file.id}" 
                            data-filename="${file.filename}" 
                            data-path="${file.path}" 
                            data-duration="${file.duration}">
                        <i class="fas fa-play"></i> 试听
                    </button>
                    <button class="btn btn-sm btn-outline-danger delete-audio" 
                            data-id="${file.id}" 
                            data-filename="${file.filename}">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        });
        
        // 绑定试听和删除按钮事件
        document.querySelectorAll('.preview-audio').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                const filename = this.getAttribute('data-filename');
                const path = this.getAttribute('data-path');
                const duration = this.getAttribute('data-duration');
                
                previewAudio(id, filename, path, duration);
            });
        });
        
        document.querySelectorAll('.delete-audio').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                const filename = this.getAttribute('data-filename');
                
                deleteAudio(id, filename);
            });
        });
    }
    
    // 上传音频文件
    function uploadAudio() {
        const fileInput = document.getElementById('audio-file');
        const file = fileInput.files[0];
        
        if (!file) {
            alert('请选择要上传的音频文件');
            return;
        }
        
        // 验证文件
        if (!validateAudioFile(file)) {
            return;
        }
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('audio_file', file);
        
        // 上传文件
        fetch('/api/upload_audio', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('上传失败');
            }
        })
        .then(data => {
            alert('音频文件上传成功');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('uploadModal'));
            modal.hide();
            // 重新加载音频文件列表
            loadAudioFiles();
        })
        .catch(error => {
            console.error('上传音频文件失败:', error);
            alert('上传音频文件失败: ' + error.message);
        });
    }
    
    // 验证音频文件
    function validateAudioFile(file) {
        // 检查文件大小（限制为100MB）
        if (file.size > 100 * 1024 * 1024) {
            alert('音频文件大小不能超过100MB');
            return false;
        }
        
        // 检查文件扩展名
        const validExtensions = ['.mp3', '.wav', '.ogg'];
        const fileName = file.name.toLowerCase();
        const isValidExtension = validExtensions.some(ext => fileName.endsWith(ext));
        
        if (!isValidExtension) {
            alert('不支持的音频格式，仅支持: MP3, WAV, OGG');
            return false;
        }
        
        return true;
    }
    
    // 试听音频
    function previewAudio(id, filename, path, duration) {
        // 设置当前试听信息
        currentPreview = {
            id: id,
            filename: filename,
            path: path,
            duration: duration
        };
        
        // 更新模态框内容
        document.getElementById('previewModalLabel').textContent = `试听音频 - ${filename}`;
        document.getElementById('preview-filename').textContent = filename;
        document.getElementById('preview-duration').textContent = duration > 0 ? `${duration}秒` : '未知';
        
        // 重置播放控制
        document.getElementById('preview-play').disabled = false;
        document.getElementById('preview-stop').disabled = true;
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('previewModal'));
        modal.show();
    }
    
    // 播放试听音频
    function playPreviewAudio() {
        const volume = document.getElementById('preview-volume').value;
        
        // 发送播放请求
        fetch('/api/play_audio', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                file_path: currentPreview.path,
                volume: parseInt(volume)
            })
        })
        .then(response => {
            if (response.ok) {
                // 更新按钮状态
                document.getElementById('preview-play').disabled = true;
                document.getElementById('preview-stop').disabled = false;
            } else {
                throw new Error('播放失败');
            }
        })
        .catch(error => {
            console.error('播放音频失败:', error);
            alert('播放音频失败: ' + error.message);
        });
    }
    
    // 停止试听音频
    function stopPreviewAudio() {
        // 发送停止播放请求
        fetch('/api/stop_audio', {
            method: 'POST'
        })
        .then(response => {
            if (response.ok) {
                // 更新按钮状态
                document.getElementById('preview-play').disabled = false;
                document.getElementById('preview-stop').disabled = true;
            } else {
                throw new Error('停止播放失败');
            }
        })
        .catch(error => {
            console.error('停止播放失败:', error);
            alert('停止播放失败: ' + error.message);
        });
    }
    
    // 删除音频文件
    function deleteAudio(id, filename) {
        if (confirm(`确定要删除音频文件 "${filename}" 吗？`)) {
            fetch(`/api/audio_files/${id}`, {
                method: 'DELETE'
            })
            .then(response => {
                if (response.ok) {
                    alert('音频文件删除成功');
                    loadAudioFiles(); // 重新加载音频文件列表
                } else {
                    throw new Error('删除失败');
                }
            })
            .catch(error => {
                console.error('删除音频文件失败:', error);
                alert('删除音频文件失败: ' + error.message);
            });
        }
    }
    
    // 更新音量显示
    function updateVolumeDisplay() {
        const volume = document.getElementById('preview-volume').value;
        document.getElementById('volume-value').textContent = `${volume}%`;
    }
    
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 加载音频文件列表
        loadAudioFiles();
        
        // 绑定按钮事件
        document.getElementById('refresh-audio').addEventListener('click', loadAudioFiles);
        document.getElementById('upload-audio').addEventListener('click', function() {
            // 清空文件选择
            document.getElementById('audio-file').value = '';
            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('uploadModal'));
            modal.show();
        });
        document.getElementById('upload-btn').addEventListener('click', uploadAudio);
        document.getElementById('preview-play').addEventListener('click', playPreviewAudio);
        document.getElementById('preview-stop').addEventListener('click', stopPreviewAudio);
        document.getElementById('preview-volume').addEventListener('input', updateVolumeDisplay);
    });
</script>
{% endblock %}